#include "notepad.h"
#include "ui_notepad.h"



Notepad::Notepad(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::Notepad)
{
    ui->setupUi(this);
    connect(ui->newAction,&QAction::triggered,this,&Notepad::newActionSlot);
    connect(ui->openAction,&QAction::triggered,this,&Notepad::openActionSlot);
    connect(ui->saveAction,&QAction::triggered,this,&Notepad::saveActionSlot);
    connect(ui->helpAction,&QAction::triggered,this,&Notepad::helpActionSlot);
    connect(ui->backAction,&QAction::triggered,this,&Notepad::backActionSlot);
}

Notepad::~Notepad()
{
    delete ui;
}



void Notepad::newActionSlot()
{
    ui->textEdit->clear();
    this->setWindowTitle("新建文本文档.txt");

}


void Notepad::openActionSlot()
{
    QString fileName=QFileDialog::getOpenFileName(this,tr("选择一个文件"),QCoreApplication::applicationFilePath(),"*.cpp *.txt");

    if(fileName.isEmpty())
    {
        QMessageBox::warning(this,"警告","请选择一个文件");

    }else{
        //qDebug()<<filename;
        QFile file(fileName);
        file.open(QIODevice::ReadOnly);
        QByteArray ba=  file.readAll();
        ui->textEdit->setText(QString(ba));
        file.close();

    }
}


void Notepad::saveActionSlot()
{
    QString fileName=QFileDialog::getSaveFileName(this,"选择一个文件",QCoreApplication::applicationFilePath());

    if(fileName.isEmpty())
    {
        QMessageBox::warning(this,"警告","请选择一个文件");
    }
    else
    {
        QFile file(fileName);
        file.open(QIODevice::WriteOnly);
        // ui->textEdit->toPlainText();
        QByteArray ba;
        ba.append((ui->textEdit->toPlainText()).toUtf8());
        file.write(ba);
        file.close();


    }
}

void Notepad::keyPressEvent(QKeyEvent *k)
{
    if(k->modifiers()==Qt::ControlModifier&& k->key()==Qt::Key_S)
    {
        saveActionSlot();
    }

    if(k->modifiers()==Qt::ControlModifier&& k->key()==Qt::Key_O)
    {
        openActionSlot();
    }
    if(k->modifiers()==Qt::ControlModifier&& k->key()==Qt::Key_N)
    {
        openActionSlot();
    }
    if(k->modifiers()==Qt::ControlModifier&& k->key()==Qt::Key_H)
    {
        helpActionSlot();
    }
    if(k->modifiers()==Qt::ControlModifier&& k->key()==Qt::Key_B)
    {
        backActionSlot();
    }

}

void Notepad::mousePressEvent(QMouseEvent *m)
{
    QPoint pt=m->pos();
    qDebug()<<pt;

    if(m->button()==Qt::LeftButton)
    {
        qDebug()<<"左键";

    }

    if(m->button()==Qt::RightButton)
    {
        qDebug()<<"右键";

    }
}


void Notepad::helpActionSlot()
{
   qDebug()<<"还没写";
    ui->textEdit->setText("123\n12334");
}

void Notepad::backActionSlot()
{
    this->hide();
    Widget *w=new Widget;
    w->show();

}
